<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>4.字符串和文本 | Cucy的博客</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="python">
    <meta name="description" content="4.字符串和文本标签： python

4.1.1 问题将一个字段分隔成多个字段，但是分隔符不确定，">
<meta property="og:type" content="article">
<meta property="og:title" content="4.字符串和文本">
<meta property="og:url" content="http://zhourudong.cn/2016/08/22/4-字符串和文本/index.html">
<meta property="og:site_name" content="Cucy的博客">
<meta property="og:description" content="4.字符串和文本标签： python

4.1.1 问题将一个字段分隔成多个字段，但是分隔符不确定，">
<meta property="og:updated_time" content="2019-02-22T05:28:07.824Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="4.字符串和文本">
<meta name="twitter:description" content="4.字符串和文本标签： python

4.1.1 问题将一个字段分隔成多个字段，但是分隔符不确定，">
    
        <link rel="alternate" type="application/atom+xml" title="Cucy的博客" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.6.13">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.png">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">cucy</h5>
          <a href="mailto:292016176@qq.com" title="292016176@qq.com" class="mail">292016176@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/cucy" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">4.字符串和文本</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">4.字符串和文本</h1>
        <h5 class="subtitle">
            
                <time datetime="2016-08-22T05:58:40.000Z" itemprop="datePublished" class="page-time">
  2016-08-22
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#4-字符串和文本"><span class="post-toc-number">1.</span> <span class="post-toc-text">4.字符串和文本</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-1-1-问题"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">4.1.1 问题</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-1-2-解决方案"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">4.1.2 解决方案</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-2-1-问题"><span class="post-toc-number">1.2.1.</span> <span class="post-toc-text">4.2.1 问题</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-2-2-解决方案"><span class="post-toc-number">1.2.2.</span> <span class="post-toc-text">4.2.2 解决方案</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-3-用shell通配符匹配字符串"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">4.3 用shell通配符匹配字符串</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-3-1-问题"><span class="post-toc-number">1.3.1.</span> <span class="post-toc-text">4.3.1 问题</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-3-2-解决方案"><span class="post-toc-number">1.3.2.</span> <span class="post-toc-text">4.3.2 解决方案</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-4-字符串匹配和搜索"><span class="post-toc-number">1.4.</span> <span class="post-toc-text">4.4 字符串匹配和搜索</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-4-1-问题"><span class="post-toc-number">1.4.1.</span> <span class="post-toc-text">4.4.1 问题</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-4-2-解决方案"><span class="post-toc-number">1.4.2.</span> <span class="post-toc-text">4.4.2 解决方案</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-5-字符串搜索和替换"><span class="post-toc-number">1.5.</span> <span class="post-toc-text">4.5 字符串搜索和替换</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-5-1"><span class="post-toc-number">1.5.1.</span> <span class="post-toc-text">4.5.1</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-5-2-解决方案"><span class="post-toc-number">1.5.2.</span> <span class="post-toc-text">4.5.2 解决方案</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-6-字符串忽略大小写的搜索替换"><span class="post-toc-number">1.6.</span> <span class="post-toc-text">4.6 字符串忽略大小写的搜索替换</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-6-1-问题"><span class="post-toc-number">1.6.1.</span> <span class="post-toc-text">4.6.1 问题</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-6-2-解决方案"><span class="post-toc-number">1.6.2.</span> <span class="post-toc-text">4.6.2 解决方案</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-8-多行匹配"><span class="post-toc-number">1.7.</span> <span class="post-toc-text">4.8 多行匹配</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-8-1-问题"><span class="post-toc-number">1.7.1.</span> <span class="post-toc-text">4.8.1 问题</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-8-2-解决方案"><span class="post-toc-number">1.7.2.</span> <span class="post-toc-text">4.8.2 解决方案</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#4-11-删除字符串不需要的字符"><span class="post-toc-number">1.8.</span> <span class="post-toc-text">4.11 删除字符串不需要的字符</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#4-11-1-问题"><span class="post-toc-number">1.8.1.</span> <span class="post-toc-text">4.11.1 问题</span></a></li></ol></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-4-字符串和文本"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">4.字符串和文本</h1>
        <div class="post-meta">
            <time class="post-time" title="2016-08-22 13:58:40" datetime="2016-08-22T05:58:40.000Z"  itemprop="datePublished">2016-08-22</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="4-字符串和文本"><a href="#4-字符串和文本" class="headerlink" title="4.字符串和文本"></a>4.字符串和文本</h1><p>标签： python</p>
<hr>
<h2 id="4-1-1-问题"><a href="#4-1-1-问题" class="headerlink" title="4.1.1 问题"></a>4.1.1 问题</h2><p>将一个字段分隔成多个字段，但是分隔符不确定，<br><a id="more"></a></p>
<h2 id="4-1-2-解决方案"><a href="#4-1-2-解决方案" class="headerlink" title="4.1.2 解决方案"></a>4.1.2 解决方案</h2><p>string对象的split()方法只适应简单的字段分割情况，当有多个分隔符，或者分隔符周围又不确定的空格时；最好使用re.split<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">line = <span class="string">'asdf fjdk; afed, fjek,asdf, foo'</span></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line">a = re.split(<span class="string">r'[;,\s]\s*'</span>, line)</span><br><span class="line"><span class="keyword">print</span> a</span><br><span class="line"></span><br><span class="line">[<span class="string">'asdf'</span>, <span class="string">'fjdk'</span>, <span class="string">'afed'</span>, <span class="string">'fjek'</span>, <span class="string">'asdf'</span>, <span class="string">'foo'</span>]</span><br></pre></td></tr></table></figure></p>
<ul>
<li style="list-style: none"><input type="checkbox" checked> 以上分隔符：</li>
<li>[</li>
<li>；</li>
<li>，</li>
<li>\s</li>
<li>\s* 多个空格符</li>
</ul>
<h3 id="4-2-1-问题"><a href="#4-2-1-问题" class="headerlink" title="4.2.1 问题"></a>4.2.1 问题</h3><p>匹配字符串开头或者结尾</p>
<h3 id="4-2-2-解决方案"><a href="#4-2-2-解决方案" class="headerlink" title="4.2.2 解决方案"></a>4.2.2 解决方案</h3><figure class="highlight python"><table><tr><td class="code"><pre><span class="line">str.startswith()        <span class="comment"># 匹配开头</span></span><br><span class="line">str.endswith()          <span class="comment"># 匹配结尾</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>filename = <span class="string">'sapm.txt'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>filename.endswith(<span class="string">'.txt'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>filename.startswith(<span class="string">'file:'</span>)</span><br><span class="line"><span class="keyword">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>url = <span class="string">'http://www.zhourudong.cn'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>url.startswith(<span class="string">'http:'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>匹配多种规则<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> os</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>filenames = os.listdir(<span class="string">'.'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>filenames</span><br><span class="line">[ <span class="string">'Makefile'</span>, <span class="string">'foo.c'</span>, <span class="string">'bar.py'</span>, <span class="string">'spam.c'</span>, <span class="string">'spam.h'</span> ]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>[name <span class="keyword">for</span> name <span class="keyword">in</span> filenames <span class="keyword">if</span> name.endswith((<span class="string">'.c'</span>, <span class="string">'.h'</span>)) ]</span><br><span class="line">[<span class="string">'foo.c'</span>, <span class="string">'spam.c'</span>, <span class="string">'spam.h'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>any(name.endswith(<span class="string">'.py'</span>) <span class="keyword">for</span> name <span class="keyword">in</span> filenames)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure></p>
</blockquote>
<ul>
<li><p>类似方法</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 方法1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>filename = <span class="string">'spam.txt'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>filename[<span class="number">-4</span>:] == <span class="string">'.txt'</span></span><br><span class="line"><span class="keyword">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>url = <span class="string">'http://www.python.org'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>url[:<span class="number">5</span>] == <span class="string">'http:'</span> <span class="keyword">or</span> url[:<span class="number">6</span>] == <span class="string">'https:'</span> <span class="keyword">or</span> url[:<span class="number">4</span>] == <span class="string">'ftp:'</span></span><br><span class="line"><span class="keyword">True</span></span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"><span class="comment"># 方法2: 使用正则表达式匹配</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> re</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>url = <span class="string">'http://www.python.org'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>re.match(<span class="string">'http:jhttps:jftp:'</span>, url)</span><br><span class="line">&lt;_sre.SRE_Match object at <span class="number">0x101253098</span>&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>检测目录内是否有指定的文件类型(结尾)</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> any(name.endswith((<span class="string">'.c'</span>, <span class="string">'.h'</span>)) <span class="keyword">for</span> name <span class="keyword">in</span> listdir(dirname)):</span><br><span class="line">...</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="4-3-用shell通配符匹配字符串"><a href="#4-3-用shell通配符匹配字符串" class="headerlink" title="4.3 用shell通配符匹配字符串"></a>4.3 用shell通配符匹配字符串</h2><h3 id="4-3-1-问题"><a href="#4-3-1-问题" class="headerlink" title="4.3.1 问题"></a>4.3.1 问题</h3><p>使用 Unix Shell 中常用的通配符 (比如 <em>.py , Dat[0-9]</em>.csv 等) 去匹配文本字符串</p>
<h3 id="4-3-2-解决方案"><a href="#4-3-2-解决方案" class="headerlink" title="4.3.2 解决方案"></a>4.3.2 解决方案</h3><p>fnmatch 模块提供了两个函数—— fnmatch() 和 fnmatchcase() ，可以用来实现这样的匹配。用法如下：<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> fnmatch <span class="keyword">import</span> fnmatch, fnmatchcase</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fnmatch(<span class="string">'foo.txt'</span>, <span class="string">'*.txt'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fnmatch(<span class="string">'foo.txt'</span>, <span class="string">'?oo.txt'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fnmatch(<span class="string">'Dat45.csv'</span>, <span class="string">'Dat[0-9]*'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>names = [<span class="string">'Dat1.csv'</span>, <span class="string">'Dat2.csv'</span>, <span class="string">'config.ini'</span>, <span class="string">'foo.py'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>[name <span class="keyword">for</span> name <span class="keyword">in</span> names <span class="keyword">if</span> fnmatch(name, <span class="string">'Dat*.csv'</span>)]</span><br><span class="line">[<span class="string">'Dat1.csv'</span>, <span class="string">'Dat2.csv'</span>]</span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 注意*nux 系统区分大小写</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># On OS X (Mac)</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fnmatch(<span class="string">'foo.txt'</span>, <span class="string">'*.TXT'</span>)</span><br><span class="line"><span class="keyword">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># On Windows</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>fnmatch(<span class="string">'foo.txt'</span>, <span class="string">'*.TXT'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure></p>
<h2 id="4-4-字符串匹配和搜索"><a href="#4-4-字符串匹配和搜索" class="headerlink" title="4.4 字符串匹配和搜索"></a>4.4 字符串匹配和搜索</h2><h3 id="4-4-1-问题"><a href="#4-4-1-问题" class="headerlink" title="4.4.1 问题"></a>4.4.1 问题</h3><p>需要匹配或者搜索特定模式的文本</p>
<h3 id="4-4-2-解决方案"><a href="#4-4-2-解决方案" class="headerlink" title="4.4.2 解决方案"></a>4.4.2 解决方案</h3><p>你想匹配的是字面字符串，那么你通常只需要调用基本字符串方法就行，比如str.find() , str.endswith() , str.startswith() 或者类似的方法：<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>text = <span class="string">'yeah, but no, but yeah, but no, but yeah'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># Exact match</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text == <span class="string">'yeah'</span></span><br><span class="line"><span class="keyword">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># Match at start or end</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text.startswith(<span class="string">'yeah'</span>)</span><br><span class="line"><span class="keyword">True</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text.endswith(<span class="string">'no'</span>)</span><br><span class="line"><span class="keyword">False</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># Search for the location of the first occurrence</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text.find(<span class="string">'no'</span>)</span><br><span class="line"><span class="number">10</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>对于复杂的匹配需要使用正则表达式和 re 模块。为了解释正则表达式的基本原理，假设你想匹配数字格式的日期字符串比如 11/27/2012 ，你可以这样做：<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>text1 = <span class="string">'11/27/2012'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text2 = <span class="string">'Nov 27, 2012'</span></span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> re</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="comment"># Simple matching: \d+ means match one or more digits</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">if</span> re.match(<span class="string">r'\d+/\d+/\d+'</span>, text1):</span><br><span class="line"><span class="meta">... </span>print(<span class="string">'yes'</span>)</span><br><span class="line"><span class="meta">... </span><span class="keyword">else</span>:</span><br><span class="line"><span class="meta">... </span>print(<span class="string">'no'</span>)</span><br><span class="line">...</span><br><span class="line">yes</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">if</span> re.match(<span class="string">r'\d+/\d+/\d+'</span>, text2):</span><br><span class="line"><span class="meta">... </span>print(<span class="string">'yes'</span>)</span><br><span class="line"><span class="meta">... </span><span class="keyword">else</span>:</span><br><span class="line"><span class="meta">... </span>print(<span class="string">'no'</span>)</span><br><span class="line">...</span><br><span class="line">no</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="4-5-字符串搜索和替换"><a href="#4-5-字符串搜索和替换" class="headerlink" title="4.5 字符串搜索和替换"></a>4.5 字符串搜索和替换</h2><h3 id="4-5-1"><a href="#4-5-1" class="headerlink" title="4.5.1"></a>4.5.1</h3><p>你想在字符串中搜索和匹配指定的文本模式</p>
<h3 id="4-5-2-解决方案"><a href="#4-5-2-解决方案" class="headerlink" title="4.5.2 解决方案"></a>4.5.2 解决方案</h3><ul>
<li><p>对于简单的字面模式，直接使用 str.repalce() 方法即可，比如：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>text = <span class="string">'yeah, but no, but yeah, but no, but yeah'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text.replace(<span class="string">'yeah'</span>, <span class="string">'yep'</span>)</span><br><span class="line"><span class="string">'yep, but no, but yep, but no, but yep'</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>对于复杂的模式，请使用 re 模块中的 sub() 函数。为了说明这个，假设你想将形式为 11/27/2012 的日期字符串改成 2012-11-27 。示例如下：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>text = <span class="string">'Today is 11/27/2012. PyCon starts 3/13/2013.'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> re</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>re.sub(<span class="string">r'(\d+)/(\d+)/(\d+)'</span>, <span class="string">r'\3-\1-\2'</span>, text)</span><br><span class="line"><span class="string">'Today is 2012-11-27. PyCon starts 2013-3-13.'</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>说明：sub() 函数中的第一个参数是被匹配的模式，第二个参数是替换模式。反斜杠数字比如  n3 指向前面模式的捕获组号。</p>
<h2 id="4-6-字符串忽略大小写的搜索替换"><a href="#4-6-字符串忽略大小写的搜索替换" class="headerlink" title="4.6 字符串忽略大小写的搜索替换"></a>4.6 字符串忽略大小写的搜索替换</h2><h3 id="4-6-1-问题"><a href="#4-6-1-问题" class="headerlink" title="4.6.1 问题"></a>4.6.1 问题</h3><p>你需要以忽略大小写的方式搜索与替换文本字符串</p>
<h3 id="4-6-2-解决方案"><a href="#4-6-2-解决方案" class="headerlink" title="4.6.2 解决方案"></a>4.6.2 解决方案</h3><p>为了在文本操作时忽略大小写，你需要在使用 re模块的时候给这些操作提供re.IGNORECASE 标志参数。比如：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>text = <span class="string">'UPPER PYTHON, lower python, Mixed Python'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>re.findall(<span class="string">'python'</span>, text, flags=re.IGNORECASE)</span><br><span class="line">[<span class="string">'PYTHON'</span>, <span class="string">'python'</span>, <span class="string">'Python'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>re.sub(<span class="string">'python'</span>, <span class="string">'snake'</span>, text, flags=re.IGNORECASE)</span><br><span class="line"><span class="string">'UPPER snake, lower snake, Mixed snake'</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>最后的那个例子揭示了一个小缺陷，替换字符串并不会自动跟被匹配字符串的大小写保持一致。为了修复这个，你可能需要一个辅助函数，就像下面的这样：</strong></p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">matchcase</span><span class="params">(word)</span>:</span></span><br><span class="line">	<span class="function"><span class="keyword">def</span> <span class="title">replace</span><span class="params">(m)</span>:</span></span><br><span class="line">		text = m.group()</span><br><span class="line">		<span class="keyword">if</span> text.isupper():</span><br><span class="line">			<span class="keyword">return</span> word.upper()</span><br><span class="line">		<span class="keyword">elif</span> text.islower():</span><br><span class="line">			<span class="keyword">return</span> word.lower()</span><br><span class="line">		<span class="keyword">elif</span> text[<span class="number">0</span>].isupper():</span><br><span class="line">			<span class="keyword">return</span> word.capitalize()</span><br><span class="line">		<span class="keyword">else</span>:</span><br><span class="line">			<span class="keyword">return</span> word</span><br><span class="line">	<span class="keyword">return</span> replace</span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>下面使用上述函数的方法：</strong></p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>re.sub(<span class="string">'python'</span>, matchcase(<span class="string">'snake'</span>), text, flags=re.IGNORECASE)</span><br><span class="line"><span class="string">'UPPER SNAKE, lower snake, Mixed Snake'</span></span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="4-8-多行匹配"><a href="#4-8-多行匹配" class="headerlink" title="4.8 多行匹配"></a>4.8 多行匹配</h2><h3 id="4-8-1-问题"><a href="#4-8-1-问题" class="headerlink" title="4.8.1 问题"></a>4.8.1 问题</h3><p>你正在试着使用正则表达式去匹配一大块的文本，而你需要跨越多行去匹配。</p>
<h3 id="4-8-2-解决方案"><a href="#4-8-2-解决方案" class="headerlink" title="4.8.2 解决方案"></a>4.8.2 解决方案</h3><p>这个问题很典型的出现在当你用点 (.) 去匹配任意字符的时候，忘记了点 (.) 不能匹配换行符的事实。比如，假设你想试着去匹配 C 语言分割的注释：<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>comment = re.compile(<span class="string">r'/\*(.*?)\*/'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text1 = <span class="string">'/* this is a comment */'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>text2 = <span class="string">'''/* this is a</span><br><span class="line"><span class="meta">... </span>multiline comment */</span><br><span class="line"><span class="meta">... </span>'''</span></span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>comment.findall(text1)</span><br><span class="line">[<span class="string">' this is a comment '</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>comment.findall(text2)</span><br><span class="line">[]</span><br><span class="line">&gt;&gt;&gt;</span><br><span class="line"><span class="comment"># 解决方法</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>comment = re.compile(<span class="string">r'/\*(.*?)\*/'</span>, re.DOTALL)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>comment.findall(text2)</span><br><span class="line">[<span class="string">' this is a\n multiline comment '</span>]</span><br></pre></td></tr></table></figure></p>
<h2 id="4-11-删除字符串不需要的字符"><a href="#4-11-删除字符串不需要的字符" class="headerlink" title="4.11 删除字符串不需要的字符"></a>4.11 删除字符串不需要的字符</h2><h3 id="4-11-1-问题"><a href="#4-11-1-问题" class="headerlink" title="4.11.1 问题"></a>4.11.1 问题</h3><p>你想去掉文本字符串开头，结尾或者中间不想要的字符，比如空白。</p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-02-22T05:28:07.824Z" itemprop="dateUpdated">2019-02-22 13:28:07</time>
</span><br>


        
        <a href="/2016/08/22/4-字符串和文本/" target="_blank" rel="external">http://zhourudong.cn/2016/08/22/4-字符串和文本/</a>
        
    </div>
    <footer>
        <a href="http://zhourudong.cn">
            <img src="/img/avatar.png" alt="cucy">
            cucy
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/python/">python</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2016/08/22/4-字符串和文本/&title=《4.字符串和文本》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2016/08/22/4-字符串和文本/&title=《4.字符串和文本》 — Cucy的博客&source=4.字符串和文本标签： python

4.1.1 问题将一个字段分隔成多个字段，但是分隔符不确定，" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2016/08/22/4-字符串和文本/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《4.字符串和文本》 — Cucy的博客&url=http://zhourudong.cn/2016/08/22/4-字符串和文本/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2016/08/22/4-字符串和文本/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2016/08/22/5-数字日期和时间/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">5.数字日期和时间</h4>
      </a>
    </div>
  

  
</nav>



    














</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/img/wechat.jpg" data-alipay="/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>cucy &copy; 2016 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2016/08/22/4-字符串和文本/&title=《4.字符串和文本》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2016/08/22/4-字符串和文本/&title=《4.字符串和文本》 — Cucy的博客&source=4.字符串和文本标签： python

4.1.1 问题将一个字段分隔成多个字段，但是分隔符不确定，" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2016/08/22/4-字符串和文本/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《4.字符串和文本》 — Cucy的博客&url=http://zhourudong.cn/2016/08/22/4-字符串和文本/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2016/08/22/4-字符串和文本/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://zhourudong.cn/2016/08/22/4-字符串和文本/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="/js/main.min.js?v=1.6.13"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.6.13" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
